const sys = require(`./system.js`)
const title = '抢奖金转卖'
const $ = sys.$(title)

//require("global-agent/bootstrap");
//const ip = 'http://47.101.210.61:7890'
//global.GLOBAL_AGENT.HTTP_PROXY=ip
//console.log('global', global.GLOBAL_AGENT)

sys.run($, 'task:resell', (resList, cookie, index, username, password, item) => {
  return new Promise(async resolve => {
    const page = 1
    const size = 10
    const showCount = 10
    const buyUsername = item.buyUsername
    console.log('配置信息', {
      page: page,
      size: size,
      showCount: showCount,
      top: item.top,
      a10: item.a10,
      a15: item.a15,
      watch: item.watch,
    })

    // 查询转卖列表
    let resp1 = await $.publicJS.buyTransferList($, cookie, page, size, '2', 'bt.awardRate')
    const rows = resp1.items.rows
    let data = resp1.items.data
    console.log(`查了 ${data.length} 条, 共有 ${rows} 条`)

    // map 转换对象属性
    data = data.map((it, idx) => {
      // const user = userList.find(uIt => uIt.id === it.createUser.id)
      const deadLineStr = it.equities.deadLine.substring(0, 10)
      const tDay = parseInt((new Date(deadLineStr) - new Date()) / 60 / 60 / 24 / 1000)
      const calDateNow = parseInt((new Date() - new Date(it.calDate)) / 1000)
      return {
        index: idx,
        id: it.id,
        // 到期时间
        deadLineStr: deadLineStr,
        tDay: tDay,
        amount: it.amount,
        rate: it.equities.rate,
        awardRate: it.awardRate,
        awardAmount: it.awardAmount,
        calDate: it.calDate,
        calDateNow: calDateNow,
        calDateNowStr: `${calDateNow} 秒 / ${(calDateNow / 60).toFixed(2)} 分钟 / ${(calDateNow / 3600).toFixed(2)} 小时`,
        // 用户信息
        my: [3293].includes(it.createUser.id) ? '是' : '否',
        userId: it.createUser.id,
        // userPhone: user.phone,
        // userWechatNickName: user.wechatNickName,
        // userCreatedDateStr: user.createdDateStr,
        // userCurrentAmountStr: user.userCurrentAmountStr,
        // userHistoryAmountStr: user.historyAmountStr,
      }
    })

    data = data.sort((a1, a2) => {
      // a1 - a2 正序 1 -> 2 -> 3 (小到大)
      // a2 - a1 倒序 3 -> 2 -> 1 (大到小)
      // 奖励：大到小， 天数：小到大
      return a2.awardRate - a1.awardRate || a1.tDay - a2.tDay
    })
    console.log(`Top.${showCount} data 数据`, data.filter((it, idx) => idx < showCount))

    // 购买 cookie
    const buyCookie = await $.publicJS.checkCookie($, $.localStorage.get(`${buyUsername}-cookie`, 'localStorage'), buyUsername, password)

    // 1. top 5 && 有奖励 && 小于 400 天
    const topList = await syncFilterBuy(buyCookie, data, 'top', item.top.count, item.top.rate, item.top.day, item.top.now, null, true)
    if (topList.length > 0) {
      resList.push({ 'top': topList })
    }

    return resolve(resList)
  })
}, (resList) => {
  console.log('任务结束 resList:', JSON.stringify(resList, null, 2))
  const resListStr = JSON.stringify(resList, null, 2)
  if (resList && resList.length > 0) {
    $.notify.sendNotify(title, resListStr)
  }
})

/**
 * 转卖 day=0
 * @param {*} cookie 
 * @returns 
 */
function syncTranDay0(cookie) {
  return new Promise(async resolve => {
    const tranData = (await $.publicJS.canTransferList($, cookie, 1, "buyDate-2")).data
    const fData = tranData.map(item => {
      const dateStr = item.buyDate.substring(0, 10)
      const tDay = parseInt((new Date() - new Date(dateStr)) / 60 / 60 / 24 / 1000)
      return {
        tDay: tDay,
        dateStr: dateStr,
        id: item.id,
      }
    }).filter(item => item.tDay === 0)
    console.log('转卖 day=0, data', fData.length, fData)
    for (let index = 0; index < fData.length; index++) {
      const item = fData[index]
      const bidTranResp = await $.publicJS.bidTransfer($, cookie, item.id)
      console.log(`转卖 day=0, index:${index}`, bidTranResp, item.id)
    }
    resolve(true)
  })
}

/**
 * 过滤抢购
 * @param {*} cookie 
 * @param {*} list 
 * @param {*} tag 标志， top / 10 / 15
 * @param {*} count Top 才需要。过滤 N 条数据
 * @param {*} rate 0.0001 ~ 0.3 = 0.01% - 30% (经常 0.0001 或 0.0002, 偶尔 0.005)
 * @param {*} day 60 天到期时间
 * @param {*} now 150 秒 之后再购买 (有缘的自然会买到)
 * @param {*} nh 年华
 * @param {*} isBuy 是否购买
 * @returns 
 */
function syncFilterBuy(cookie, list, tag = 'top', count, rate, day, now, nh, isBuy) {
  return new Promise(async resolve => {
    // 过滤数据
    const fList = list.filter((item, index) => {
      let is = true
      if (count) {
        is = is && index < count
      }
      if (rate) {
        is = is && item.awardRate >= rate
      }
      if (day) {
        is = is && item.tDay < day
      }
      if (now) {
        is = is && item.calDateNow > now
      }
      if (nh) {
        is = is && item.rate == nh
      }
      return is
    })
    console.log(`${tag}-list`, fList.length, fList)
    const buyList = []
    for (let index = 0; index < fList.length; index++) {
      const item = fList[index]
      let buyResp = { message: '---' }
      if (isBuy) {
        buyResp = await $.publicJS.buyTransferCode($, cookie, item.id)
        console.log(`${tag}-${index}-buyResp`, buyResp, item)
      }
      buyList.push({
        '转卖ID': item.id,
        '权益剩余天数': item.tDay,
        '权益金额': item.amount,
        '权益年华': item.rate,
        '转卖额比': item.awardRate,
        '转卖额奖': item.awardAmount,
        '转卖时长': item.calDateNowStr,

        '用户ID': item.userId,
        '用户微信昵称': item.userWechatNickName,
        '用户创建时间': item.userCreatedDateStr,
        '用户当前资产': item.userCurrentAmountStr,
        '用户历史资产': item.historyAmountStr,
        '购买结果': buyResp.message,
      })
    }
    resolve(buyList)
  })
}

/**
 * 设置用户列表
 * @param {*} cookie 
 * @param {*} list 
 * @returns 
 */
function syncSetUserList(cookie, list) {
  return new Promise(async resolve => {
    let userList = $.localStorage.get('task:userList', 'localStorageInfo')
    for (let idx = 0; idx < list.length; idx++) {
      const it = list[idx]
      let user = userList.find(uIt => uIt.id === it.createUser.id) || {}
      // 用户不存在
      if (!user.phone) {
        console.log('用户不存在', it.createUser.id)
        const userPhoneListResp = await $.publicJS.userPhoneList($, cookie)
        const userPhoneList = userPhoneListResp.map(it => {
          const now = parseInt((new Date() - new Date(it.createdDate)) / 1000)
          return {
            id: it.id,
            createdDate: it.createdDate,
            createdDateStr: `${(now / 3600 / 24).toFixed(2)} 天 / ${(now / 3600 / 24 / 365).toFixed(2)} 年`,
            phone: it.phone,
            userCurrentAmount: it.userCurrentAmount,
            userCurrentAmountStr: `${(it.userCurrentAmount / 10000).toFixed(2)}万`,
            historyAmount: it.historyAmount,
            historyAmountStr: `${(it.historyAmount / 10000).toFixed(2)}万`,
            headImg: it.headImg,
            wechatNickName: it.wechatNickName,
          }
        })
        userList.push(...userPhoneList)
        userList = $.publicJS.unique(userList, "id").map((it, idx) => ({ index: idx, ...it, }))
        $.localStorage.set('task:userList', userList, 'localStorageInfo')
      }
    }
    resolve(userList)
  })
}